﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

using System.Data;
using System.Data.SqlClient;

using TimKen.App;
using TimKen.BussLogic;
using System.Collections;

namespace TimKen.Web
{
    public partial class POptionListSearch : TimKen.App.WebPage
    {
        private POptionManager optionManager = new POptionManager();
        public PCategoryManager pcm = new PCategoryManager();

        /// <summary>
        /// 分类ID
        /// </summary>
        public int CategoryID
        {
            get
            {
                if (ViewState["CategoryID"] != null)
                    return Convert.ToInt32(ViewState["CategoryID"]);
                else
                    return 0;
            }
            set
            {
                ViewState["CategoryID"] = value;
            }
        }


        public int BrandID
        {
            get
            {
                if (ViewState["BrandID"] != null && TypeParse.IsNumeric(ViewState["BrandID"]))
                    return Convert.ToInt32(ViewState["BrandID"]);
                else
                    return 0;
            }
            set
            {
                ViewState["BrandID"] = value;
            }
        }



        public string OptionIDValueWhere
        {
            get
            {
                if (ViewState["OptionIDValueWhere"] != null)
                    return ViewState["OptionIDValueWhere"].ToString();
                else
                    return "";
            }
            set
            {
                ViewState["OptionIDValueWhere"] = value;
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["CategoryID"] != null)
                {
                    try
                    {
                        CategoryID = int.Parse(Request.Params["CategoryID"]);
                    }
                    catch
                    {
                        Alert(GetLangString("InvalidCategoryID"), "Error.aspx");
                    }
                }
                else
                {
                    CategoryID = int.Parse(Request.Params["CategoryID"]);
                }

                lbParentList.Text = GetParentLink(pcm.GetAllParent(CategoryID, LanguageID));

                if (Request.QueryString["BrandID"] != null)
                {
                    if (TypeParse.IsNumeric(Request.Params["BrandID"]))
                    {
                        BrandID = int.Parse(Request.Params["BrandID"]);
                    }
                    else
                    {
                        Response.Redirect("Error.aspx");
                    }
                }
            }

            BindResources();
            if (!string.IsNullOrEmpty(Request.Form["OptionID"]) && !string.IsNullOrEmpty(Request.Form["OptionValue"]))
            {
                OptionIDValueWhere = OptionIDValueWhere + " AND  a.ProductID IN (SELECT  ProductID FROM V_PCategoryAttributeRel   WHERE CategoryID=" + CategoryID + " AND LanguageID=" + LanguageID + " AND  OptionID=" + Request.Form["OptionID"] + " AND OptionValue='" + Request.Form["OptionValue"] + "') ";
            }
            int flag = -1;
            DataSet ds = optionManager.GetSearchableListByCategory(CategoryID, LanguageID, OptionIDValueWhere, ref   flag, BrandID);



            //如果没有扩展属性,则直接跳转到产品列表
            if (ds == null || ds.Tables[0].Rows.Count == 0)
                Response.Redirect("Product.aspx?type=2&CategoryID=" + CategoryID + "&brandID=" + BrandID);

            ///显示符合当前条件的产品数量
            string sql = "SELECT  COUNT(DISTINCT  ProductID) FROM V_PCategoryAttributeRel  AS a   WHERE a.CategoryID=" + CategoryID + " AND a.LanguageID=" + LanguageID;

            if (BrandID != 0)
                sql += "  and  a.BrandID=" + BrandID;


            if (!string.IsNullOrEmpty(OptionIDValueWhere))
                sql += OptionIDValueWhere;

            object pcount = DataAccess.DbHelperSQL.GetSingle(sql);

            //如果为属性多选查询,则链接查看所有产品的地址要改变  by miao at 09.1.7
            //if (!string.IsNullOrEmpty(OptionIDValueWhere))
            //    this.linkProductList.HRef = "ProductList.aspx?feedfdf=" + Tools.Encrypt(OptionIDValueWhere) + "&CategoryID=" + CategoryID + "&brandID=" + BrandID;
            //else
            //    this.linkProductList.HRef = "ProductList.aspx?type=2&CategoryID=" + CategoryID + "&brandID=" + BrandID;

            //如果为空,则显示友好提示 
            if (ds == null || ds.Tables[0].Rows.Count == 0)
                this.ltEmptyData.Visible = true;

            //如果已经没有多选属性值,则跳转到产品页面
            if (flag == 0)
            {
                if (!string.IsNullOrEmpty(OptionIDValueWhere))
                    OptionIDValueWhere = Tools.Encrypt(OptionIDValueWhere);
                Response.Redirect("Product.aspx?feedfdf=" + OptionIDValueWhere + "&CategoryID=" + CategoryID + "&brandID=" + BrandID, true);
            }

            //绑定属性值列表
            this.dlOptionList.DataSource = ds;
            this.dlOptionList.DataBind();
        }


        public string GetString(string values, string id)
        {
            string[] array = values.Split('^');

            Array.Sort(array, new StringComparer());

            if (array.Length == 1)
                return values;
            StringBuilder sb = new StringBuilder();
            sb.Append("<table width='100%'   class='optiontable'>");


            int i = 0;
            for (i = 0; i < array.Length; i++)
            {
                if (i / 10.0 == 0)
                    sb.Append("<tr>");

                string value = array[i];
                string href = "<td><a href=\"javascript:submitPage('{0}','{1}')\">{1}</a></td>";
                href = string.Format(href, id, value);
                sb.Append(href);

                if ((i + 1) % 10.0 == 0)
                    sb.Append("</tr>");
            }

            if (i % 10.0 != 0)
            {
                for (int j = 0; j < 10 - (i % 10); j++)
                    sb.Append("<td></td>");
                sb.Append("</tr>");
            }
            sb.Append("</table>");

            return sb.ToString();
        }

        private string GetParentLink(string linkData)
        {
            string[] links = linkData.Split(',');
            StringBuilder sb = new StringBuilder();
            if (links.Length > 0)
            {
                sb.Append("<a href=\"Category.aspx?\">" + GetLangString("ProductCategories") + "</a>&nbsp;—&nbsp;");//产品分类
                for (int i = 0; i < links.Length; i++)
                {
                    string link = links[i];
                    string[] nameid = link.Split(':');

                    if (nameid.Length == 2 && i != links.Length - 1)
                    {
                        sb.Append("<a href=\"ChildCategory.aspx?cid=" + nameid[1] + "&brandid=" + BrandID + "\">" + nameid[0] + "</a>&nbsp;—&nbsp;");
                    }
                    else
                    {
                        sb.Append(nameid[0] + "&nbsp;—&nbsp;");
                    }
                }
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 7, 7);
            }
            return sb.ToString();
        }

        protected void BindResources()
        {
            this.ltEmptyData.Text = GetLangString("EmptyData");
        }

        public class StringComparer : IComparer
        {

            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            ///<summary>
            ///比较两个字符串，如果含用数字，则数字按数字的大小来比较。
            ///</summary>
            ///<param name="x"></param>
            ///<param name="y"></param>
            ///<returns></returns>
            int IComparer.Compare(Object x, Object y)
            {
                if (x == null || y == null)
                    throw new ArgumentException("Parameters can't be null");

                string fileA = x as string;
                string fileB = y as string;
                char[] arr1 = fileA.ToCharArray();
                char[] arr2 = fileB.ToCharArray();

                int i = 0, j = 0;
                while (i < arr1.Length && j < arr2.Length)
                {
                    if (char.IsDigit(arr1[i]) && char.IsDigit(arr2[j]))
                    {
                        string s1 = "", s2 = "";
                        while (i < arr1.Length && char.IsDigit(arr1[i]))
                        {
                            s1 += arr1[i];
                            i++;
                        }
                        while (j < arr2.Length && char.IsDigit(arr2[j]))
                        {
                            s2 += arr2[j];
                            j++;
                        }

                        if (int.Parse(s1) > int.Parse(s2))
                        {
                            return 1;
                        }

                        if (int.Parse(s1) < int.Parse(s2))
                        {
                            return -1;
                        }

                    }
                    else
                    {
                        if (arr1[i] > arr2[j])
                        {
                            return 1;
                        }

                        if (arr1[i] < arr2[j])
                        {
                            return -1;
                        }
                        i++;
                        j++;

                    }

                }

                if (arr1.Length == arr2.Length)
                {
                    return 0;
                }
                else
                {
                    return arr1.Length > arr2.Length ? 1 : -1;
                }

                //            return string.Compare( fileA, fileB );
                //            return( (new CaseInsensitiveComparer()).Compare( y, x ) );
            }
        }
    }
}